﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NPOI.SS.UserModel;
using Prism.Services.Dialogs;
using SmartPlant.Core;
using SmartPlant.Core.ViewModels;
using SmartPlant.Model;
using SmartPlant.Model.Biz;
using SmartPlant.Services;
using SmartPlant.Services.Interfaces;
using SmartPlant.WinCore;

namespace SmartPlant.Modules.Base.ViewModels
{
    public class NewLoopViewModel : SmartDialogBase
    {
        public ObservableCollection<UnitTagConvention> UnitTagConventions { get; set; }
        public decimal _proId { get; set; }
        public decimal _unitId { get; set; }
        public IUnitTagConvService _unitTagConv { get; set; }
        private readonly IDialogService dialogService;
        private ILoopService _loopService;
        private decimal _copyfromId = 0;
        private bool isBusy = true;
        public bool IsBusy
        {
            get { return isBusy; }
            set
            {
                isBusy = value;
                RaisePropertyChanged();
            }
        }

        public NewLoopViewModel(IDialogService dialogService, IUnitTagConvService unitTagConv, ILoopService loopService)
        {
            UnitTagConventions = new ObservableCollection<UnitTagConvention>();
            _proId = GlobalObject.CurrentProject.ProjId;
            this.dialogService = dialogService;
            _unitTagConv = unitTagConv;
            _loopService = loopService;
        }

        public override async void ExecuteCloseDialogCommand(string parameter)
        {
            IsBusy = true;
            ButtonResult result = ButtonResult.None;
            DialogParameters parameters = new DialogParameters();
            if (parameter?.ToLower() == "true")
            {
                var emptyitem = UnitTagConventions.FirstOrDefault(p => p.IsReadOnly != true & p.Text.Length == 0);
                if (emptyitem != null)
                {
                    var tempTagConventions = UnitTagConventions.Where(p => p.IsReadOnly != true).ToList();
                    int index = tempTagConventions.IndexOf(emptyitem) + 1;
                    if (index != tempTagConventions.Count)
                    {
                        dialogService.ShowMessage($"名称第{index}部分，未填写！");
                        IsBusy = false;
                        return;
                    }
                }
                string loopName = string.Concat(
                    UnitTagConventions.Select(p =>
                    {
                        if (p.Text.Length > 0 & p.Text.Length < p.FuncParm2)
                        {
                            return p.Text.PadRight((int)p.FuncParm2, ' ');
                        }
                        return p.Text;
                    })
                );
                var lastSegmentSeparator = UnitTagConventions.Last(x => x.separator);
                if (loopName.EndsWith(lastSegmentSeparator?.Text))
                {
                    loopName = loopName.Substring(0, loopName.Length - lastSegmentSeparator.Text.Length);//后缀没有时，不需要带出最后那个分隔符号
                }
                decimal? newLoopId = 0;
                var rES = await _loopService.CreateLoopAsync(_proId, _unitId, loopName, _copyfromId);
                if (rES.statusCode == 200)
                {
                    newLoopId = rES.data;
                    parameters.Add(DialogParameterKeys.Id, newLoopId);
                }
                else
                {
                    dialogService.ShowMessage(rES.errors);//不正常结果，比如位号重复等。 
                    IsBusy = false;
                    return;

                }
          
                result = ButtonResult.Yes;
            }
            else if (parameter?.ToLower() == "false")
            {
                result = ButtonResult.No;
            }
            RraiseRequestClose(new DialogResult(result, parameters));
            IsBusy = false;
        }

        public override async void OnDialogOpened(IDialogParameters parameters)
        {
            Title = parameters.GetValue<string>(DialogParameterKeys.Title);
            _copyfromId = parameters.GetValue<decimal>(DialogParameterKeys.Id);
            _unitId = parameters.GetValue<decimal>("unitId");
            var x = await _unitTagConv.GetUnitTagConventionsAsync(_proId, _unitId, ObjectDefId.loop);
            foreach (var item in x)
            {
                if (!string.IsNullOrEmpty(item.UnitPreffix))
                {
                    UnitTagConventions.Add(new UnitTagConvention() { Text = item.UnitPreffix, IsReadOnly = true, separator = true });
                }
                if (item.TAG_CONV_ATTR_REF == "PLANT_AREA_UNIT.UNIT_ID" && _unitId == GlobalObject.CurrentUnit.UnitId)
                {
                    //某一段是unit No，且刚好和要创建的那个unit为一个
                    item.Text = GlobalObject.CurrentUnit.UnitNum.ToString();
                }
                UnitTagConventions.Add(item);
            }
            base.OnDialogOpened(parameters);
            IsBusy = false;
        }
    }
}
